package com.qf.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.inject.internal.cglib.core.$Block;
import com.qf.annotation.RequiresPermissionsDesc;
import com.qf.pojo.DtsAdmin;
import com.qf.pojo.DtsPermission;
import com.qf.pojo.DtsRole;
import com.qf.pojo.DtsStorage;
import com.qf.service.DtsAdminService;
import com.qf.service.DtsPermissionService;
import com.qf.service.DtsRoleService;
import com.qf.service.DtsStorageService;
import com.qf.util.JacksonUtil;
import com.qf.util.Permission;
import com.qf.util.PermissionUtil;
import com.qf.util.ResponseUtil;
import com.qf.util.bcrypt.BCryptPasswordEncoder;
import com.qf.vo.CatVo;
import com.qf.vo.PermVo;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.SimpleFormatter;
import java.util.stream.Collectors;

/**
 * @author 邢式瑞
 * @version 1.0
 * @project E-commercebackGroundManagementSystem
 * @date 2022/9/22 9:16
 */
@RestController
@RequestMapping("/admin")
@CrossOrigin
public class AdminController {
    @Autowired
    private DtsAdminService dtsAdminService;
    @Autowired
    private DtsRoleService dtsRoleService;
    @Autowired
      private ApplicationContext applicationContext;
    @Autowired
     private DtsPermissionService dtsPermissionService;
    @RequiresPermissionsDesc(menu = {"系统管理","管理员"},button = "查询")
    @RequiresPermissions("admin:admin:list")
    @GetMapping("/admin/list")
    public Object adminList(Integer page, Integer limit, String sort, String order, String username) {
        Page<DtsAdmin> dtsAdminPage = dtsAdminService.selectAdminPage(page, limit, sort, order, username);
        long total = dtsAdminPage.getTotal();
        List<DtsAdmin> records = dtsAdminPage.getRecords();
        HashMap<String, Object> data = new HashMap<>();
        data.put("total", total);
        data.put("items", records);
        return ResponseUtil.ok(data);
    }

    @RequiresPermissionsDesc(menu = {"系统管理","管理员"},button = "添加")
    @RequiresPermissions("admin:admin:create")
    @PostMapping("/admin/create")
    public Object insert(@RequestBody DtsAdmin dtsAdmin) {
        if(dtsAdmin==null){
            return ResponseUtil.badArgumentValue();
        }
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        dtsAdmin.setPassword(bCryptPasswordEncoder.encode(dtsAdmin.getPassword()));
        dtsAdmin.setAddTime(new Date());
        dtsAdmin.setUpdateTime(new Date());
        dtsAdminService.insertAdmin(dtsAdmin);
        return ResponseUtil.ok(dtsAdmin);
    }
    @RequiresPermissionsDesc(menu = {"系统管理","管理员"},button = "编辑")
    @RequiresPermissions("admin:admin:update")
    @PostMapping("/admin/update")
    public Object updateAdmin(@RequestBody DtsAdmin dtsAdmin) {
        if(dtsAdmin==null){
            return ResponseUtil.badArgumentValue();
        }
        dtsAdmin.setUpdateTime(new Date());
        dtsAdminService.updateAdmin(dtsAdmin);

        return ResponseUtil.ok();
    }
    @RequiresPermissionsDesc(menu = {"系统管理","管理员"},button = "删除")
    @RequiresPermissions("admin:admin:delete")
    @PostMapping("/admin/delete")
    public Object delete( @RequestBody DtsAdmin dtsAdmin) {
        if(dtsAdmin==null){
            return ResponseUtil.badArgumentValue();
        }
        dtsAdmin.setDeleted(true);
        System.out.println(dtsAdmin+"===========================================");
        dtsAdminService.deleteAdmin(dtsAdmin);
        return ResponseUtil.ok();
    }

    @GetMapping("/role/options")
    public Object Role() {

        List<CatVo> dtsRoles = dtsRoleService.findCatVoList();

//        HashMap<String, Object> data = new HashMap<>();
//    data.put("data",dtsRoles);
        return ResponseUtil.ok(dtsRoles);
    }
    @RequiresPermissionsDesc(menu = {"系统管理","角色管理"},button = "查询")
    @RequiresPermissions("admin:role:list")
    @GetMapping("/role/list")
    public Object roleList(int page, int limit, String sort, String order) {

        IPage<DtsRole> items = dtsRoleService.findRoleList(page, limit, sort, order);
        Map data = new HashMap<>();
        data.put("total", items.getTotal());
        data.put("items", items.getRecords());
        return ResponseUtil.ok(data);
    }
    @RequiresPermissionsDesc(menu = {"系统管理","角色管理"},button = "添加")
    @RequiresPermissions("admin:role:create")
    @PostMapping("/role/create")
    public Object createRole(@RequestBody String body) {
        if(StringUtils.isEmpty(body)){
            return ResponseUtil.fail(404,"存在空值");
        }
        String name = JacksonUtil.parseString(body, "name");
        if(StringUtils.isEmpty(name)){
            return ResponseUtil.fail(404,"存在空值");
        }
        String desc = JacksonUtil.parseString(body, "desc");

        DtsRole dtsRole = new DtsRole();
        dtsRole.setDesc(desc);
        dtsRole.setName(name);


        Date date = new Date();

        dtsRole.setAddTime(date);
        dtsRole.setUpdateTime(date);
        dtsRoleService.createRole(dtsRole);
        return ResponseUtil.ok(dtsRole);
    }
    @RequiresPermissionsDesc(menu = {"系统管理","角色管理"},button = "编辑")
    @RequiresPermissions("admin:role:update")
    @PostMapping("/role/update")
    public Object updateRole(@RequestBody DtsRole dtsRole) {

        System.out.println();
        if(dtsRole==null){
            return ResponseUtil.badArgumentValue();
        }
        dtsRole.setUpdateTime(new Date());
        dtsRoleService.updateRole(dtsRole);
        return ResponseUtil.ok();
    }
    @RequiresPermissionsDesc(menu = {"系统管理","角色管理"},button ="删除")
   @RequiresPermissions("admin:role:delete")
    @PostMapping("/role/delete")
    public Object deleteRole(@RequestBody DtsRole dtsRole) {
        if(dtsRole==null){
            return ResponseUtil.badArgumentValue();
        }
     dtsRole.setDeleted(true);
     dtsRoleService.deleteRole(dtsRole);
 return ResponseUtil.ok();
    }

    @GetMapping("/role/permissions")
    public Object permissionsRole(Integer roleId ){
        if(roleId==null){
            return ResponseUtil.badArgumentValue();
        }
       Set<String> presSet  = dtsPermissionService.findDtsPremissionByRoleId(roleId);
        System.out.println(presSet);

        System.out.println(presSet);
        List<Permission> permissions = PermissionUtil.listPermission(applicationContext, "com.qf");
        System.out.println(permissions);

//        for (Permission permission : permissions) {
//            System.out.println(permission);
//        }
        List<String> assignedPermissions = permissions.stream().map(permission -> {
            return permission.getRequiresPermissions().value()[0];
        }).collect(Collectors.toList());
       List<PermVo> permVoList = PermissionUtil.listPermVo(permissions);
        System.out.println(permVoList);

        Map data = new HashMap();
        data.put("systemPermissions",permVoList);
        if(presSet.contains("*")){

            data.put("assignedPermissions",assignedPermissions);
            System.out.println(data);

            return  ResponseUtil.ok(data);

        }


        //data.put("systemPermissions",permVoList);
        data.put("assignedPermissions",presSet);

        return ResponseUtil.ok(data);
//        Map data = new HashMap();
//        String basicPackage = "com.qf";
//        List<Permission> permissions = PermissionUtil.listPermission(applicationContext,basicPackage);
//        System.out.println(permissions);
//        //1:查询当前角色所拥有的所有权限
//        Set<String> permSet =  dtsPermissionService.findDtsPremissionByRoleId(roleId);
//        List<PermVo> permVoList = PermissionUtil.listPermVo(permissions);
//        //2:当前系统中暂时拥有的所有权限
//        List<String> assignedPermissions = permissions.stream().map(permission -> {
//            return permission.getRequiresPermissions().value()[0];
//        }).collect(Collectors.toList());
//        if(permSet.contains("*")){
//            //当前角色拥有的权限
//            data.put("assignedPermissions",assignedPermissions);
//        }else{
//            //2:判断当前角色拥有的所有权限在总权限中是否存在
//            Set<String> permRoleId = permSet.stream().filter(perm -> {
//                if (assignedPermissions.contains(perm)) {
//                    return true;//有 留下
//                } else {
//                    return false;//没有 去掉
//                }
//            }).collect(Collectors.toSet());
//            //当前角色拥有的权限
//            data.put("assignedPermissions",permRoleId);
//        }
//        data.put("systemPermissions",permVoList);//显示二级菜单 及功能
//        return ResponseUtil.ok(data);
    }

    @PostMapping("/role/permissions")
    public Object permissions(@RequestBody String body){
        if(StringUtils.isEmpty(body)){
            return ResponseUtil.badArgumentValue();
        }
        List<String> permissions = JacksonUtil.parseStringList(body, "permissions");
        Integer roleId = JacksonUtil.parseInteger(body, "roleId");
        dtsPermissionService.updatePermissionByRoleId(roleId,permissions);
        return ResponseUtil.ok();
    }
    @PostMapping("/profile/password")
    public  Object updatePwd(@RequestBody  String body ){
        String newPassword = JacksonUtil.parseString(body, "newPassword");
        String newPassword2 = JacksonUtil.parseString(body, "newPassword2");
        String oldPassword = JacksonUtil.parseString(body, "oldPassword");
        Subject subject = SecurityUtils.getSubject();
        DtsAdmin dtsAdmin= (DtsAdmin)subject.getPrincipal();
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
    // DtsAdmin dtsAdmin=    dtsAdminService.selectAdminByPwd(bCryptPasswordEncoder.encode(oldPassword));

     if(!newPassword.equals(newPassword2)){
         return ResponseUtil.badArgumentValue();

     }
     dtsAdmin.setPassword(bCryptPasswordEncoder.encode(newPassword));
     dtsAdminService.updateAdmin(dtsAdmin);
     return ResponseUtil.ok();
    }


}
